package com.wenbo.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.wenbo.model.Relationship;
import com.wenbo.model.UserInfo;

public class UserInfoDaoImpl extends BasicDao<UserInfo> implements IUserInfoDao 
{

	@Override
	public UserInfo findUserInfoByName(final String name) 
	{
		@SuppressWarnings("unchecked")
		List<UserInfo> userInfos = this.getHibernateTemplate().executeFind(new HibernateCallback() 
	    {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
			    return  session.createQuery("from UserInfo u where u.userName=?")
				.setString(0,name).list();
			}
		});
		if(userInfos.size() == 0)
		{
			return null;
		}
		return userInfos.get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<UserInfo> findUserFrinds(final UserInfo userInfo) 
	{
		List<Relationship> objects = this.getHibernateTemplate().executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException 
			{
				return session.createQuery("from Relationship r where r.userId = ?")
				.setInteger(0, userInfo.getId())
				.list();
			}
		});
		List<UserInfo> userInfos = new ArrayList<UserInfo>();
		for(Relationship obj:objects)
		{
			userInfos.add(this.load(obj.getFriendId()));
		}
		return userInfos;
	}
    
}
